﻿using System.Windows;
using SHomeWorkshop.LunarPresentation.Dialogs;
using System.Windows.Media;
using SHomeWorkshop.LunarPresentation.Adorners;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media.Imaging;

namespace SHomeWorkshop.LunarPresentation.Commands
{
    public partial class Command
    {
        public static void PageSetting()
        {
            if (Globals.selectedEditor == null) return;
            if (Globals.selectedEditor.RootPanel == null)
            {
                MessageBox.Show("发现意外情况，无法对当前文档进行页面设置——当前文档根面板为空！", Globals.appName,
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            PageSettingDialog ppsDlg = new PageSettingDialog(Globals.selectedEditor) { Owner = Globals.MainWindow };
            ppsDlg.ShowDialog();
        }

        public static void PrintSelectedDocument()
        {
            if (Globals.selectedEditor == null)
            {
                MessageBox.Show("当前未打开任何文档！", Globals.appName, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if ((Globals.selectedEditor.DefaultBackground != Brushes.White &&
                Globals.selectedEditor.DefaultBackground != Brushes.Transparent) ||
                Globals.selectedEditor.ExFontSize > 14)
            {
                MessageBoxResult r = Dialogs.LunarMsgBox.MsgBoxShow(
                    Globals.appName,
                    "打印当前文档会较浪费打印机耗材，真的要继续打印吗？",
                    "当前文档背景色不是白色或透明色，或者字号大于14，这样打印会严重浪费打印耗材。",
                    "您可以考虑先将编辑器配色方案改为白底黑字（命令：bdhz）或缩小字号再打印。\r\n" +
                    "——要缩小字号，请将主界面右下角的“字号缩放滑块条”拖动到最左侧。",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Warning);
                if (r != MessageBoxResult.Yes) return;
            }

            PreviewAndPrintDocument(Globals.selectedEditor);
        }

        public static void PreviewAndPrintDocument(Editor masterEditor)
        {
            if (masterEditor == null) return;

            System.Windows.Media.Imaging.RenderTargetBitmap rtb = Commands.Command.GetExpressionImage(masterEditor.RootPanel);

            if (rtb == null)
            {
                MessageBox.Show("发生意外错误，未能获取当前文档的图形，无法继续打印！",
                    Globals.appName, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            // PixelFormats.Pbgra32

            Rect wholeRect = new Rect(0, 0, rtb.PixelWidth, rtb.PixelHeight);

            PaperInfo curPaperInfo = PaperInfo.GetPaperInfo(
                masterEditor.PaperSizeLineAdorner.PaperName);

            int width, height;
            if (masterEditor.PaperSizeLineAdorner.PaperDirection == Orientation.Horizontal)
            {
                width = curPaperInfo.LongSidePixcelCount;
                height = curPaperInfo.ShortSidePixcelCount;
            }
            else
            {
                height = curPaperInfo.LongSidePixcelCount;
                width = curPaperInfo.ShortSidePixcelCount;
            }

            //取出页面宽、高
            int paperWidth = width;
            int paperHeight = height;

            Thickness margin = new Thickness(
                masterEditor.PageSettingInfo.MarginLeft,
                masterEditor.PageSettingInfo.MarginTop,
                masterEditor.PageSettingInfo.MarginRight,
                masterEditor.PageSettingInfo.MarginBottom
                );

            //Wpf是96DPI，而我要打印的图像是300DPI。3.25是比例值。
            width = (int)(width - margin.Left * 3.25 - margin.Right * 3.25);
            height = (int)(height - margin.Top * 3.25 - margin.Bottom * 3.25);

            PrintPreviewDialog pd = new PrintPreviewDialog() { Owner = Globals.MainWindow };

            pd.mainDocViewer.ShowPageBorders = true;

            int offcetX = 0, offcetY = 0;

            bool endX = false;
            bool endY = false;

            do
            {
                int realHeight;

                if (offcetY + height > wholeRect.Height)
                {
                    realHeight = (int)wholeRect.Height - offcetY;
                    endY = true;
                }
                else
                {
                    realHeight = height;
                }

                do
                {
                    int realWidth;

                    if (offcetX + width > wholeRect.Width)
                    {
                        realWidth = (int)wholeRect.Width - offcetX;
                        endX = true;
                    }
                    else
                    {
                        realWidth = width;
                    }

                    Int32Rect pieceRect;

                    if (width <= 0 || height <= 0) break;

                    pieceRect = new Int32Rect(offcetX, offcetY, realWidth, realHeight);
                    var array = new byte[realWidth * realHeight * rtb.Format.BitsPerPixel / 8];//每像素需要32位（4字节）。

                    rtb.CopyPixels(pieceRect, array, realWidth * rtb.Format.BitsPerPixel / 8, 0);

                    //跨度，每行像素数据的总字节数
                    //int stride = rtb.PixelWidth * rtb.Format.BitsPerPixel / 8;
                    //stride += 4 - stride % 4; //补上几个字节，使其可以被4整除 

                    var newBitmapImage = BitmapImage.Create(realWidth, realHeight, 300, 300,
                        PixelFormats.Pbgra32, null, array, realWidth * rtb.Format.BitsPerPixel / 8);

                    FixedPage fp = new FixedPage() { Width = paperWidth * 96 / 300, Height = paperHeight * 96 / 300 };
                    Image newImg = new Image() { Source = newBitmapImage };

                    Thickness realMargin = margin;

                    if (masterEditor.PageSettingInfo.HorizontalCenter == true)
                    {
                        realMargin.Left = realMargin.Right = (paperWidth - realWidth) / 6.5;//6.5=3.25*2
                    }

                    if (masterEditor.PageSettingInfo.VerticalCenter == true)
                    {
                        realMargin.Top = realMargin.Bottom = (paperHeight - realHeight) / 6.5;
                    }

                    newImg.Margin = realMargin;

                    fp.Children.Add(newImg);

                    pd.MainDoc.Pages.Add(
                        new System.Windows.Documents.PageContent()
                        {
                            Child = fp
                        });
                    offcetX += width;

                } while (offcetX <= wholeRect.Width && endX == false);

                offcetY += height;
                offcetX = 0; endX = false;
            } while (offcetY <= wholeRect.Height && endY == false);

            pd.ShowDialog();
        }
    }
}
